<template>
  <div>
    <!-- 搜索和新增部分 -->
    <el-row class="search_content">
      <el-col :span="8">
        编号:
        <el-input
          v-model.trim="lease_id"
          placeholder="请输入内容"
          :clearable="true"
          size="mini"
          maxlength="11"
          @keydown.enter.native="search"
        ></el-input>
      </el-col>
      <el-col :span="8">
        客户名:
        <el-input
          v-model.trim="clientName"
          placeholder="请输入内容"
          :clearable="true"
          size="mini"
          maxlength="11"
          @keydown.enter.native="search"
        ></el-input>
      </el-col>
      <el-col :span="4">
        花卉名:
        <el-input
          v-model.trim="flowerName"
          placeholder="请输入内容"
          size="mini"
          :clearable="true"
          maxlength="11"
          @keydown.enter.native="search"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button
          size="mini"
          class="search_btn"
          type="primary"
          plain
          @click="search"
          >搜索</el-button
        ></el-col
      >
      <el-col :span="2">
        <el-button
          type="primary"
          @click="openAdd"
          class="fr add_btn"
          size="mini"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="2">
        <!-- <el-button
          type="primary"
          @click="openAdd"
          class="fr add_btn"
          size="mini"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
         @click="exportUser"
          class="fr add_btn"
          size="mini"
        >
          导出
        </el-button> -->
      </el-col>
    </el-row>
    <!-- 列表显示客户信息 -->
    <!-- 注selection-change为选择项改变时的事件 stripe为斑马纹 -->
    <el-table id="el-table" :data="lists" @selection-change="getIds" stripe>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline>
            <el-form-item label="花卉名">
              <span>{{ props.row.flowerClassifyList[0].flower_name }}</span>
            </el-form-item>
            <el-form-item label="所属分类">
              <span>{{ props.row.classify[0].classify_name }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.create_time | formatDate }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55px"></el-table-column>
      <el-table-column label="租赁编号" prop="lease_id"></el-table-column>
      <el-table-column
        label="花卉"
        prop="flowerClassifyList[0].flower_name"
      ></el-table-column>
      <el-table-column
        label="客户名"
        prop="clientList[0].client_name"
      ></el-table-column>
      <el-table-column
        label="单价(元/值)"
        prop="lease_unit_price"
      ></el-table-column>
      <el-table-column label="数量(值)" prop="count"></el-table-column>
      <el-table-column label="租期(月)" prop="duration"></el-table-column>
      <el-table-column label="总价(元)" prop="total_price"></el-table-column>
      <el-table-column label="到期时间" prop="expiration_date">
        <template slot-scope="scope">
          <span>{{ scope.row.expiration_date | formatDate1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="findOldLease(scope.row)"
            >修改</el-button
          >
          <el-button type="text" @click="delLease(scope.row)">删除</el-button>
          <el-button
            type="text"
            v-if="permission[2] == 1"
            @click="changePwd(scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" align="middle" id="bottom">
    <!-- 批量删除 -->
      <el-col :span="4" :push="3">
        <el-button type="danger" size="mini" @click="batchDelete()"
          >批量删除</el-button
        >
      </el-col>
      <!-- 分页栏 -->
      <el-col :span="8" :push="6">
        <el-pagination
          @size-change="pageSizeChange"
          @current-change="currPageChange"
          :current-page="curr_page"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 去顶部 -->
    <div class="back top" @click="top" v-show="!gotop" title="go顶部">
      <i class="el-icon-arrow-up"></i>
    </div>
    <!-- 去底部 -->
    <div class="back bottom" v-show="gotop" @click="bottom" title="go底部">
      <i class="el-icon-arrow-down"></i>
    </div>
    <el-row>
      <!-- 租出新增抽屉 -->
      <el-drawer
        title="租出新增"
        :visible.sync="isShow"
        size="24%"
        direction="rtl"
      >
        <div class="addform">
          <el-form
            :model="params"
            :rules="rules"
            ref="addLease"
            :label-position="labelPosition"
            label-width="80px"
          >
            <el-form-item label="花卉名" >
              <template>
                <!-- 要:clearable -->
                <el-select
                  v-model="flowerNameArrs"
                  placeholder="请选择花卉"
                  size="mini"
                >
                  <el-option
                    v-for="(item, value) in flowerNameArr"
                    :key="value"
                    :label="item.flower_name"
                    :value="item.flower_id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <!-- 客户 -->
            <el-form-item label="客户">
              <template>
                <!-- 要:clearable -->
                <el-select
                  v-model="clientNameArrs"
                  placeholder="请选择客户"
                  size="mini"
                >
                  <el-option
                    v-for="(item, value) in clientNameArr"
                    :key="value"
                    :label="item.client_name"
                    :value="item.client_id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <!-- 单价 -->
            <el-form-item label="单价" prop="lease_unit_price">
              <el-input
                placeholder="请输入单价"
                v-model.trim="params.lease_unit_price"
                :clearable="true"
                maxlength="11"
                @keydown.enter.native="addLease('addLease')"
              ></el-input>
            </el-form-item>
            <!-- 数量 -->
            <el-form-item label="数量" prop="count">
              <el-input
                placeholder="请输入数量"
                v-model.trim="params.count"
                :clearable="true"
                maxlength="11"
                @keydown.enter.native="addLease('addLease')"
              ></el-input>
            </el-form-item>
            <el-form-item label="租期(月)" prop="duration">
              <el-input
                placeholder="请输入租期"
                v-model.trim="params.duration"
                :clearable="true"
                maxlength="3"
                @keydown.enter.native="addLease('addLease')"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addLease('addLease')"
                >提交</el-button
              >
              <el-button @click="resetForm('addLease')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
    </el-row>
        <!-- 修改的抽屉 -->
    <el-row>
      <el-drawer
        title="租出修改"
        :visible.sync="updateShow"
        size="25%"
        direction="rtl"
      >
        <div class="addform">
          <el-form :model="params" :rules="rules" ref="updateLease"
          :label-position="labelPosition"
            label-width="80px">
            <el-form-item label="租赁花卉" prop="flowerNameArrs">
              <!-- 下拉框 -->
              <template>
                <!-- 要:clearable -->
                <el-select
                  v-model="flowerNameArrs"
                  placeholder="请选择花卉"
                  size="mini"
                >
                  <el-option
                    v-for="(item, value) in flowerNameArr"
                    :key="value"
                    :label="item.flower_name"
                    :value="item.flower_id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <!-- 客户 -->
            <el-form-item label="客户" prop="clientNameArrs">
              <template>
                <!-- 要:clearable -->
                <el-select
                  v-model.trim="clientNameArrs"
                  placeholder="请选择花卉分类"
                  size="mini"
                >
                  <el-option
                    v-for="(item, value) in clientNameArr"
                    :key="value"
                    :label="item.client_name"
                    :value="item.client_id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <el-form-item label="单价" prop="lease_unit_price">
              <!-- @input解决视图不刷新问题 -->
              <el-input
                @input="change($event)"
                placeholder="请输入单价"
                v-model.trim="params.lease_unit_price"
                maxlength="11"
                @keydown.enter.native="updateLease('updateLease')"
              ></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="count">
              <el-input
                placeholder="请输入数量"
                v-model.trim="params.count"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="租期" prop="duration">
              <el-input
                placeholder="请输入租期"
                v-model.trim="params.duration"
                maxlength="3"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateLease('updateLease')"
                >提交</el-button
              >
              <el-button @click="resetForm('updateLease')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
    </el-row>
  </div>
</template>

<script>
// 导入http
import http from '@/utils/httpUtil'
// 导入aes
import aes from '@/utils/AESUtil.js'
export default {
  data () {
    return {
      direction: 'rtl',
      drawer: false,
      labelPosition: 'left',
      gotop: true,
      isShow: false,
      updateShow: false,
      action: {
        leaseList: 'ssmService/lease/selectPageLease',
        addLease: 'ssmService/lease/addLease',
        updateLease: 'ssmService/lease/updateLease',
        selectLeaseById: 'ssmService/lease/selectLeaseById',
        deleteLease: 'ssmService/lease/deleteLease',
        clientList: 'ssmService/client/selectPageClient',
        flowerList: 'ssmService/flower/selectFlowerClassify',
        inventoryList: 'ssmService/inventory/selectPageInventory',
        updateInventory: 'ssmService/inventory/updateInventory'
      },
      lists: [],
      listss: [],
      permission: [],
      total: 0,
      page_size: 10,
      curr_page: 1,
      flowerName: '',
      lease_id: null,
      clientName: '',
      clientNameArrs: 1,
      clientNameArr: '',
      flowerNameArrs: 1,
      flowerNameArr: '',
      params: {
        flower_id: null,
        client_id: null,
        lease_unit_price: null,
        count: null,
        duration: null,
        total_price: null,
        lease_id: null
      },
      rules: {
        lease_unit_price: [
          {
            required: true,
            message: '请输入单价',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '请输入正确的数字',
            trigger: 'blur'
          }
        ],
        count: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '请输入正确的数字',
            trigger: 'blur'
          }
        ],
        duration: [
          {
            required: true,
            message: '请输入租期',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '请输入正确的数字',
            trigger: 'blur'
          }
        ]
      },
      ids: ''
    }
  },
  mounted () {
    this.getLeaseList()
  },
  methods: {
    // 导出用户
    exportUser () {
      // 发送导出请求
      http.xhrGet(this, this.action.exportUser, null, (res) => {
        this.downloadFile(res)
      }, 'blob')
    },
    downloadFile (data) {
      if (!data) {
        return
      }
      // 创建一个a标签
      let link = document.createElement('a')
      // a标签不显示
      link.style.display = 'none'
      // a标签访问的路径为响应的媒体流地址
      link.href = data.request.responseURL
      // 设置属性
      link.setAttribute('download', '用户信息')
      // 将动态元素添加到html中
      document.body.appendChild(link)
      // 模拟点击
      link.click()
    },
    // 解决视图不刷新的问题
    change (e) {
      this.$forceUpdate()
    },
    // 去顶部
    top () {
      document.getElementById('top').scrollIntoView()
    },
    // 去底部
    bottom () {
      document.getElementById('bottom').scrollIntoView(false)
    },
    // 当前页总条数改变时函数
    pageSizeChange (pageSize) {
      this.lease_id = ''
      this.clientName = ''
      this.flowerName = ''
      this.getLeaseList(
        this.lease_id,
        this.clientName,
        this.flowerName,
        1,
        pageSize
      )
    },
    // 当前页改变时函数
    currPageChange (currPage) {
      this.lease_id = ''
      this.clientName = ''
      this.flowerName = ''
      this.getLeaseList(
        this.lease_id,
        this.clientName,
        this.flowerName,
        currPage,
        this.page_size
      )
    },
    // 获取租出列表
    getLeaseList (
      lease_id = null,
      clientName = null,
      flowerName = null,
      curr_page = 1,
      page_size = 10
    ) {
      const params = {
        curr_page: curr_page,
        page_size: page_size
      }
      if (lease_id !== null && lease_id !== '') {
        params['lease_id'] = lease_id
      }
      if (clientName !== null && clientName !== '') {
        params['client_name'] = clientName
      }
      if (flowerName !== null && flowerName !== '') {
        params['flower_name'] = flowerName
      }
      http.xhrGet(this, this.action.leaseList, params, res => {
        // console.log(res)
        // 总条数，当前页，当前页最大条数，数据
        this.total = res.data.total
        this.curr_page = res.data.pageNum
        this.page_size = res.data.pageSize
        this.lists = res.data.list
      })
      // this.updateInv(3)
    },
    // 搜索
    search () {
      let lease_id = this.lease_id
      let client_name = this.clientName
      let flower_name = this.flowerName
      // \s 代表匹配一些空白符     包括：空格、Tab、换行、回车,等价于 [\t\r\n ] 去除首尾空格
      lease_id = lease_id.replace(/(^\s*)|(\s*$)/g, '')
      client_name = client_name.replace(/(^\s*)|(\s*$)/g, '')
      flower_name = flower_name.replace(/(^\s*)|(\s*$)/g, '')
      this.getLeaseList(lease_id, client_name, flower_name, 1, 10)
    },
    selectFlowers () {
      const params = {
        curr_page: 1,
        page_size: 100
      }
      http.xhrGet(this, this.action.clientList, params, res => {
        this.clientNameArr = res.data.list
      })
      http.xhrGet(this, this.action.flowerList, params, res => {
        this.flowerNameArr = res.data.list
      })
    },
    // 新增客户
    openAdd () {
      this.selectFlowers()
      this.isShow = true
      this.clientNameArrs = 1
      this.flowerNameArrs = 1
      this.params = {
        flower_id: null,
        client_id: null,
        lease_unit_price: null,
        count: null,
        duration: null,
        total_price: null,
        lease_id: null
      }
    },
    // 重置
    resetForm (refName) {
      this.$refs[refName].resetFields()
    },
    // 修改库存
    updateInv (index) {
      const par = {
        curr_page: 1,
        page_size: 100
      }
      http.xhrGet(this, this.action.inventoryList, par, res => {
        this.listss = res.data.list
        for (let i = 0; i < this.listss.length; i++) {
          /* eslint-disable no-eqeqeq, eqeqeq */
          if (this.listss[i].flower_id == this.flowerNameArrs) {
            let rent_count = this.listss[i].rent_count
            let lease_count
            let damage_count = this.listss[i].damage_count == null ? 0 : this.listss[i].damage_count
            if (this.listss[i].lease_count != null) {
              if (index === 4) {
                lease_count = Number(this.listss[i].lease_count) - Number(this.params.count)
              }
              // for (let j = 0; j < this.lists.length; j++) {
              //   if (new Date().getTime() - this.lists[j].expiration_date >= 0) {
              //     damage_count = this.lists[j].lease_count * 0.2
              //     lease_count = this.listss[i].lease_count - damage_count
              //     console.log('c' + damage_count)
              //     console.log('d' + lease_count)
              //   }
              // }
              if (index === 1 || index === 2 || index === 3) {
                lease_count = Number(this.listss[i].lease_count) + Number(this.params.count == null ? 0 : this.params.count)
              }
            } else {
              lease_count = this.params.count == null ? 0 : this.params.count
            }
            const parm = {
              inventory_count: rent_count - damage_count - lease_count,
              damage_count: damage_count,
              lease_count: lease_count,
              inventory_id: this.listss[i].inventory_id
            }
            http.xhrPost(this, this.action.updateInventory, parm, ref => {
            })
          }
        }
      })
    },
    // 新增租出信息
    addLease (refName) {
      this.$refs[refName].validate(valid => {
        if (valid) {
          this.params.client_id = this.clientNameArrs
          this.params.flower_id = this.flowerNameArrs
          this.params.total_price =
            this.params.lease_unit_price *
            this.params.count *
            this.params.duration
          this.params.expiration_dates = new Date(new Date().getTime() + 2592000000 * this.params.duration)
          // 调用inventory修改方法
          this.updateInv(1)
          // console.log(typeof (this.params.expiration_dates))
          // console.log(this.params.expiration_dates)
          const params = this.params
          params['baseModel.token'] = aes.getRandom(16, 16)
          // 发送数据给服务器，实现新增功能
          http.xhrPost(this, this.action.addLease, params, res => {
            // 给出提示，新增成功，关闭抽屉，刷新页面，清空表单
            this.$message({
              type: 'success',
              message: res.message
            })
            this.isShow = false
            this.getLeaseList()
            // 表单重置
            // this.params = {
            //   client_name: '',
            //   lease_id: '',
            //   phone: '',
            //   type: 1
            // }
          })
        } else {
          return false
        }
      })
    },
    // 实现修改
    updateLease (refName) {
      this.$refs[refName].validate(valid => {
        if (valid) {
          this.params.flower_id = this.flowerNameArrs
          this.params.client_id = this.clientNameArrs
          this.params.total_price =
            this.params.lease_unit_price *
            this.params.count *
            this.params.duration
          this.params.expiration_dates = new Date(new Date().getTime() + 2592000000 * this.params.duration)
          this.params['baseModel.token'] = aes.getRandom(16, 16)
          // console.log('a' + this.params.count)
          // 发送修改请求
          http.xhrPost(this, this.action.updateLease, this.params, res => {
            this.$message({
              type: 'success',
              message: res.message
            })
            // this.updateInv(2)
            this.params = {
              client_name: '',
              lease_id: '',
              phone: '',
              type: 1
            }
            this.updateShow = false
            // 刷新指定页
            this.getLeaseList(
              this.lease_id,
              this.clientName,
              this.flowerName,
              this.curr_page,
              this.page_size
            )
          })
        } else {
          return false
        }
      })
    },
    // 将旧数据回显到页面上
    findOldLease (lease) {
      this.selectFlowers()
      this.updateShow = true
      // 根据userid取出最新的租出数据，因为version版本必须是最新的
      const param = {
        lease_id: lease.lease_id
      }
      http.xhrGet(this, this.action.selectLeaseById, param, res => {
        this.flowerNameArrs = res.data[0].flower_id
        this.clientNameArrs = res.data[0].client_id
        this.params.lease_unit_price = res.data[0].lease_unit_price
        this.params.count = res.data[0].count
        this.params.duration = res.data[0].duration
        this.params.version = res.data[0].version
        this.params.lease_id = res.data[0].lease_id
        // console.log(this.res.data[0].count)
        // this.updateInv(4)
      })
    },
    // 批量删除
    batchDelete () {
      if (this.ids !== '') {
        this.$confirm('您正在执行批量操作，是否继续', '提示', {
          confirmButtonText: '确认执行',
          cancelButtonText: '容我想想'
        })
          .then(() => {
            let ids = this.ids.substring(0, this.ids.length - 1)
            this.xhrDelete(ids)
          })
          .catch(() => {})
      } else {
        this.$message({
          type: 'error',
          message: '请至少选中一条'
        })
      }
    },
    // 得到所有的id
    getIds (leases) {
      // console.log(leases)
      this.ids = ''
      leases.forEach((item, index) => {
        this.ids += item.lease_id + ','
      })
    },
    // 单独删除
    delLease (leases) {
      // 询问租出是否删除
      this.$confirm('您确定要删除当前记录吗?', '确定删除?', {
        confirmButtonText: '残忍丢弃',
        cancelButtonText: '容我想想'
      })
        .then(() => {
          // 发送删除请求
          this.xhrDelete(leases.lease_id)
        })
        .catch(() => {})
    },
    // 真实删除
    xhrDelete (ids) {
      // 发送真实删除请求
      http.xhrPost(this, this.action.deleteLease + '/' + ids, null, res => {
        this.$message({
          type: 'success',
          message: res.message
        })
        this.getLeaseList(
          this.lease_id,
          this.clientName,
          this.flowerName,
          this.curr_page,
          this.page_size
        )
      })
    }
  },
  components: {
  },
  // 过滤器
  filters: {
    formatDate (value) {
      // 时间戳转换日期格式方法
      if (value == null) {
        return ''
      } else {
        let date = new Date(value)
        let y = date.getFullYear() // 年
        let MM = date.getMonth() + 1 // 月
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate() // 日
        d = d < 10 ? '0' + d : d
        let h = date.getHours() // 时
        h = h < 10 ? '0' + h : h
        let m = date.getMinutes() // 分
        m = m < 10 ? '0' + m : m
        let s = date.getSeconds() // 秒
        s = s < 10 ? '0' + s : s
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
      }
    },
    formatDate1 (value) {
      // 时间戳转换日期格式方法
      if (value == null) {
        return ''
      } else {
        let date = new Date(value)
        let y = date.getFullYear() // 年
        let MM = date.getMonth() + 1 // 月
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate() // 日
        d = d < 10 ? '0' + d : d
        return y + '-' + MM + '-' + d
      }
    }
  }
}
</script>

<style scoped>
@import "../../assets/css/reset.css";
@import "../../assets/css/client.css";
</style>
